﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 第八次作业
{
    public partial class Form1: Form
    {
        private SqlConnection connection;
        private SqlDataReader reader;
        private string currentEnglishWord;

        public Form1()
        {
            InitializeComponent();
            // 初始化数据库连接
            string connectionString = "Data Source=DESKTOP-OG9INKL;Initial Catalog=WordDB;User ID=sa;Password=Jiaokaixuan9180.";
            connection = new SqlConnection(connectionString);
            textBoxEnglish.KeyDown += textBoxEnglish_KeyDown;
            LoadNextWord();
        }
        private void LoadNextWord()
        {
            try
            {
                // 打开数据库连接
                connection.Open();
                string query = "SELECT TOP 1 English, Chinese FROM Words ORDER BY NEWID()";
                SqlCommand command = new SqlCommand(query, connection);
                reader = command.ExecuteReader();

                if (reader.Read())
                {
                    currentEnglishWord = reader["English"].ToString();
                    labelChinese.Text = reader["Chinese"].ToString();
                }
                else
                {
                    MessageBox.Show("没有更多单词了！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库错误: " + ex.Message);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                {
                    reader.Close();
                }
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }

        private void textBoxEnglish_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string userInput = textBoxEnglish.Text.Trim();
                if (userInput.Equals(currentEnglishWord, StringComparison.OrdinalIgnoreCase))
                {
                    labelResult.Text = "正确";
                }
                else
                {
                    labelResult.Text = "错误，正确答案是: " + currentEnglishWord;
                }
                textBoxEnglish.Text = "";
                LoadNextWord();
            }
        }
    }
}
